import axios from 'axios'
// import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'
// import  ElMessage  from 'element-plus'

// 创建axios实例
const http = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// axios请求拦截器
http.interceptors.request.use(config => {
  const userStore = useUserStore()
  if (userStore.userInfo.token) {
    config.headers.Authorization = `Bearer ${userStore.userInfo.token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器, 处理非200
http.interceptors.response.use(
  response => {
    if (response.data.code === '1') {
      return response.data
    } 

    ElMessage.warning(response.data.message)
    return Promise.reject(response.data)
  },
  error => {
    if (error.response?.status === 401) {
      router.push('/login')
    }

    ElMessage.error(error.response.data.message || '服务异常')
    return Promise.reject(error)
  }
)



export default http